package com.shanhai.wallpapers.fragments.download

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.shanhai.wallpapers.network.repository.PexelsRepository
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.io.File

class DownloadViewModel(private val pexelsRepository: PexelsRepository) : ViewModel() {

    private val downloadState = MutableLiveData<DownloadState>()
    val uiState: LiveData<DownloadState> get() = downloadState
    private var downloadJob: Job? = null
    fun downloadWallpaper(url: String, directory: File) {
        downloadJob = viewModelScope.launch {
            pexelsRepository.downloadWallpaper(url, directory)
                .collect { downloadResult ->
                    when (downloadResult) {
                        is DownloadResult.Progress -> emitUiState(progress = downloadResult.progress)
                        is DownloadResult.Completed -> emitUiState(file = downloadResult.file)
                        is DownloadResult.Error -> emitUiState(error = downloadResult.errMsg)
                    }
                }
        }
    }

    fun cancelDownload(){

    }

    private fun emitUiState(
        progress: Int? = null,
        file: File? = null,
        error: String? = null
    ) {
        val dataState = DownloadState(progress, file, error)
        downloadState.value = dataState
    }

    data class DownloadState(
        val progress: Int?, val file: File?, var error: String?
    )
}